#include "StompedReality/Asset/AssetManager.h"
#include "StompedReality/Asset/PatchInfo.h"
#include "StompedReality/Components/PatchComponent.h"
#include "StompedReality/Core/ComponentConstuctionHelper.h"
#include "StompedReality/Core/Graphics/BasicRenderFunctions.h"
#include "StompedReality/Core/IGame.h"
#include "StompedReality/Core/TypeSystem/TypeSystem.h"

CreateRegDummy( PatchComponent );

namespace StompedReality
{
namespace components
{

PatchComponent::PatchComponent( ) :
  Component ( )
{
}

PatchComponent::~PatchComponent( )
{
}

void PatchComponent::Draw( )
{
}

void PatchComponent::OnCreation( )
{
  Component::OnCreation( );
  this->m_PatchID = 0;
  this->m_Offset = StompedReality::Math::Vector2 ( 0, 0 );
}

void PatchComponent::OnDestruction( )
{
}

void PatchComponent::InitializeComponent( StompedReality::Core::ComponentConstuctionHelper* constructionHelper )
{
  unsigned char ro = constructionHelper->GetCurrentJsonValue( ).get( "renderOrder", 1 ).asUInt( );
  StompedReality::Asset::PatchInfo info = this->m_Game->getAssetManager( )->GetPatchInfo( this->m_PatchID );

  StompedReality::Graphics::Functions::RenderPatch* patch = new StompedReality::Graphics::Functions::RenderPatch( ro );
  patch->Offset = this->m_Offset;
  patch->PatchBinding = info.glBinding;
  patch->TextureBinding = info.textureID;

  constructionHelper->AddRenderFunction( patch );
}

void PatchComponent::Update ( )
{
}

bool PatchComponent::ProcessMessage ( StompedReality::Core::Message* msg )
{
  return true;
}

void PatchComponent::SetPatchID ( StompedReality::ID patchID )
{
  this->m_PatchID = patchID;
}

StompedReality::ID PatchComponent::GetPatchID( )
{
  return this->m_PatchID;
}

int PatchComponentReg::registeType( )
{
  return ( int ) ( StompedReality::type_system::TypeSystem::CreateTypeInfo<PatchComponent> ( "PatchComponent" )->
                   addTypeField ( StompedReality::type_system::TypeField ( "offset",
                                                                           &PatchComponent::m_Offset ) )->
                   addTypeField ( StompedReality::type_system::TypeField ( "patchID",
                                                                           &PatchComponent::m_PatchID ) ) );
}

static int typeReg = PatchComponentReg::registeType( );

}
}